package com.example.freeengine.wallpaper.fragment.common.picturelist;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import com.example.freeengine.R;
import com.example.freeengine.wallpaper.fragment.WallPaperViewModel;


/**
 * @author Terry Deng
 */
public class PictureListFragment extends Fragment {

    private WallPaperViewModel mViewModel;
    private PictureListAdapter pictureListAdapter;
    private RecyclerView recyclerView;

    public PictureListFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_picture_list, container, false);
    }

    @Override
    public void onActivityCreated(@Nullable @org.jetbrains.annotations.Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        // fragment 共享 activity 的 viewmodel
        mViewModel = new ViewModelProvider(requireActivity()).get(WallPaperViewModel.class);

        assert getArguments() != null;
        String filePath = getArguments().getString("path");
        pictureListAdapter = new PictureListAdapter(mViewModel.getWallPaperTakePictures(filePath), requireContext(), mViewModel);

        recyclerView = requireView().findViewById(R.id.takePictureRecycleView);
        recyclerView.setLayoutManager(new LinearLayoutManager(requireContext(), LinearLayoutManager.VERTICAL, false));
        recyclerView.setAdapter(pictureListAdapter);

        mViewModel.pictureListDataChange.observe(getViewLifecycleOwner(), data -> {
            if (data == 1){
                Log.i("change", "onChanged: ");
                pictureListAdapter.notifyDataSetChanged();
            }
        });

    }

}